import { Layout, Button, Row, Col, Dropdown, Menu, Modal, Avatar, Space } from 'antd';
import Login from '../pages/_login/index.js';
import { connect, useLocation, useHistory, history } from 'umi';
import { createHomeHeaderMenu } from '../utils/config';
import React, { Fragment, useState, useEffect } from 'react';
import ManageLayout from './manageLayout.js';
import { getFilePrefix } from '../utils/config';
import HomePage from '../pages/homePage';
const { pathToRegexp } = require('path-to-regexp');
const { Content, Header } = Layout;

function getLayout(pathname, isLogin) {
  // 管理中心的路由匹配
  const manageLayoutMatch = pathToRegexp('/manageCenter', [], { end: false });
  if (manageLayoutMatch.exec(pathname)) {
    if (!isLogin) {
      history.push('/homePage');
    }
    return ManageLayout;
  }
  // 如果未登录并尝试访问非homePage的路由，则重定向到ErrorPage
  const homePageMatch = pathToRegexp('/homePage/:subpath*', [], { end: false });
  if (!isLogin && !homePageMatch.exec(pathname)) {
    history.push('/homePage');
    return HomePage;
  }
  return Fragment;
}

function getDefaultMenuSelected(pathName, homeHeaderMenu) {
  let targetKey = 'homePage';
  homeHeaderMenu?.some(({ key }) => {
    const menuMatch = pathToRegexp('/' + key, [], { end: false });
    if (menuMatch.exec(pathName)) {
      targetKey = key;
      return true;
    }
  });
  return targetKey;
}

function PrimaryLayout({ children, userInfo, dispatch }) {
  const [isModal, setisModal] = useState(false);
  const [homeHeaderMenu, setHomeHeaderMenu] = useState([]);
  const location = useLocation();
  const history = useHistory();
  const pathname = location.pathname;
  const isLogin = userInfo && userInfo.userId > 0;

  useEffect(() => {
    // 当用户信息变化时，更新主页头部菜单
    setisModal(false);
    setHomeHeaderMenu(createHomeHeaderMenu(userInfo.userType));
  }, [userInfo]);

  const TargetLayout = getLayout(pathname, isLogin);
  const selectedMenu = getDefaultMenuSelected(pathname, homeHeaderMenu);
  const toPathname = (e) => {
    if (!isLogin) {
      setisModal(true);
    } else {
      history.push('/' + e.key);
    }
  }

  const items = [
    userInfo.userType !== 0 && {
      key: 'selfInformation',
      label: <Button type='link' style={{ width: '100%' }} onClick={
        () => {
          history.push({ pathname: '/attentionList/attentionDetail', state: { targetUserId: userInfo.userId } })

        }}>个人资料</Button>,

    },
    {
      key: 'logout',
      label: <Button type='link' style={{ width: '100%' }} onClick={
        () => {
          dispatch({ type: "user/logout" });
          dispatch({ type: 'manageCenter/save', payload: { lastManagePath: '', lastPathState: null } });
        }}>退出登录</Button>,

    },
  ]

  return (
    <>
      <Header style={{ backgroundColor: '#fff' }}>
        <Row>
          <Col span={4} offset={1}>
            <img src='/image/logo.png' alt='logo' style={{ width: 'auto', height: '.5rem', marginBottom: '.1rem', userSelect: 'none' }} />
            <span style={{
              fontSize: '.2rem',
              fontWeight: '650',
              marginLeft: '.1rem',
              userSelect: 'none',
            }}>ZSDN</span>
          </Col>
          <Col span={15}>
            <div style={{
              textAlign: 'center',
              marginLeft: '1rem',
            }}>
              <Menu mode="horizontal" items={homeHeaderMenu} onClick={toPathname} selectedKeys={[selectedMenu]} />
            </div>
          </Col>
          <Col span={3} style={{ textAlign: 'right' }}>
            {isLogin ? (
              <Dropdown menu={{ items }} trigger={['click']} style={{ minWidth: '120px', left: '1300px' }}
              >
                <div>
                  <Space align="center">
                    <Avatar style={{ userSelect: 'none', cursor: 'pointer' }}
                      src={userInfo.imgFilePath === "" || !userInfo.imgFilePath ? "/image/login/defaultFilePath.png" : getFilePrefix() + userInfo.imgFilePath} />
                    <span style={{
                      color: '#005CBB',
                      fontFamily: 'Arial, sans-serif',
                      fontWeight: 'bold',
                      cursor: 'pointer',
                      userSelect: 'none',
                    }}>
                      {userInfo.displayName}
                    </span>
                  </Space>
                </div>
              </Dropdown>
            ) : (
              <Button type='link' onClick={() => setisModal(true)}>请登录</Button>
            )}
          </Col>
        </Row>
      </Header >
      <Content style={{ minHeight: '80vh' }}>
        <TargetLayout>{children}</TargetLayout>
      </Content>
      <Modal key="loginModal" open={isModal} onCancel={() => setisModal(false)} footer={null} maskClosable={false}>
        <Login />
      </Modal>
    </>
  );
}

export default connect(({ user }) => ({ userInfo: user.userInfo }))(PrimaryLayout);